using DG.Tweening;
using GameFramework;
using GameFramework.Event;
using UnityEditor;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace StarForce
{
    public class Player : Entity
    {
        [SerializeField] private PlayerData m_PlayerData = null;

        private RaycastHit2D m_Rayhit;

        private readonly float m_DefaultMoveDistance = 3f;

        private bool m_IsJump;

        private Rigidbody2D m_Rigidbody2D;

        private float m_MaxY;

        private float m_MoveDistance;

        private int m_Reverse;

        private float m_ReverseTime = 3f;

        private float m_ReverseCurTime = 0;

        private bool m_IsReverse;

        protected override void OnShow(object userData)
        {
            base.OnShow(userData);
            m_PlayerData = userData as PlayerData;
            if (m_PlayerData == null)
            {
                Log.Error("Player object data is invalid.");
                return;
            }

            transform.localPosition = m_PlayerData.StartLocation;
            transform.localScale = Vector3.one * 2;
            m_IsJump = false;
            m_Rigidbody2D = transform.GetComponent<Rigidbody2D>();
            m_MaxY = transform.localPosition.y;
            SetMoveDistance();
            m_ReverseCurTime = 0;
            m_Reverse = 1;
            m_IsReverse = false;
            GameEntry.Event.Subscribe(PropEventArgs.EventId, OnProp);
        }

        private void FixedUpdate()
        {
            m_Rayhit = Physics2D.Raycast(CachedTransform.localPosition, Vector2.down, 0.2f, 1 << 9);

            if (m_Rayhit.collider != null && !m_IsJump)
            {
                if (m_Rayhit.collider.tag == "DeathGround")
                {
                    Log.Info("GameOver");
                    GameEntry.Event.Fire(this, ReferencePool.Acquire<GameOverEventArgs>());
                    GameEntry.Entity.HideEntity(this);
                }
                else
                {
                    m_Rigidbody2D.bodyType = RigidbodyType2D.Static;
                    m_IsJump = true;
                    CachedTransform.DOLocalMoveY(transform.localPosition.y + m_MoveDistance, 0.4f)
                        .SetEase(Ease.OutCubic).OnComplete(() =>
                        {
                            m_IsJump = false;
                            m_Rigidbody2D.bodyType = RigidbodyType2D.Dynamic;
                            CheckeUpScore();
                            SetMoveDistance();
                        });
                    if (m_Rayhit.collider.tag == "GroundTop")
                    {
                        GameEntry.Entity.HideEntity(((Entity) m_Rayhit.collider.gameObject.GetComponent(typeof(Entity)))
                            .Id);
                    }
                }
            }

            CameraChange();

            Vector3 p = GameEntry.Camera.MainCamera.WorldToViewportPoint(CachedTransform.localPosition);
            if (p.x > 0f && p.x < 1f) // 如果满足在屏幕内
            {
//                float Hor = Input.GetAxis("Horizontal"); //当你按‘a’'d'键返回一个[-1，1]的值
                CachedTransform.localPosition += (Vector3.right * GameEntry.InputModule.Horizontal * Time.deltaTime * 5) * m_Reverse;
            }
        }

        private void Update()
        {
            if (m_IsReverse)
            {
                if (m_ReverseCurTime < m_ReverseTime)
                {
                    m_ReverseCurTime += Time.deltaTime;
                }
                else
                {
                    m_IsReverse = false;
                    m_ReverseCurTime = 0;
                    m_Reverse = 1;
                }
            }
        }

        protected override void OnHide(bool isShutdown, object userData)
        {
            base.OnHide(isShutdown, userData);
            GameEntry.Event.Unsubscribe(PropEventArgs.EventId, OnProp);
        }

        private void OnProp(object sender, GameEventArgs e)
        {
            //触发道具效果
            PropEventArgs result = (PropEventArgs) e;
            switch (result.PropType)
            {
                case 0:
                    SetMoveDistance(3);
                    break;
                case 1:
                    m_IsReverse = true;
                    m_ReverseCurTime = 0;
                    m_Reverse = -1;
                    break;
                case 2:
                    GameEntry.Entity.ShowInk(new InkData(GameEntry.Entity.GenerateSerialId(), 7,
                        new Vector3(0, GameEntry.Camera.MainCamera.transform.position.y + 2f, 1)));
                    break;
            }
        }

        private void SetMoveDistance(int temp = 1)
        {
            m_MoveDistance = m_DefaultMoveDistance * temp;
        }

        /// <summary>
        /// 根据跳跃的高度 加分
        /// </summary>
        private void CheckeUpScore()
        {
            if (transform.localPosition.y > m_MaxY)
            {
                //加分
                int score = Mathf.FloorToInt((transform.localPosition.y - m_MaxY) * 10);
                m_MaxY = transform.localPosition.y;
                GameEntry.Event.Fire(this, ReferencePool.Acquire<UpScoreEventArgs>().Fill(score));
            }
        }

        /// <summary>
        /// 摄像机跟随移动
        /// </summary>
        private void CameraChange()
        {
            Vector3 CameraLocation = GameEntry.Camera.MainCamera.transform.localPosition;
            float cus = transform.localPosition.y - CameraLocation.y;
            //当最高点不在屏幕中央的时候 摄像机移动
            if (cus > 0.5f)
            {
                GameEntry.Camera.MainCamera.transform.DOLocalMoveY(transform.localPosition.y, 0.3f);
            }
        }

        private void OnDrawGizmos()
        {
            Debug.DrawRay(CachedTransform.position, Vector2.down * 0.2f, Color.red);
        }
    }
}